package net.aynt.blog.interceptor;

import java.lang.reflect.Method;
import java.util.Locale;
import java.util.ResourceBundle;

import net.aynt.blog.pojo.User;
import net.aynt.blog.sys.Constants;
import net.aynt.core.exception.ActionException;
import net.aynt.core.mvc.Annotation;
import net.aynt.core.mvc.IUser;
import net.aynt.core.mvc.InterceptorAdapter;
import net.aynt.core.mvc.WebContext;
import net.aynt.core.mvc.util.ResourceUtils;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.ResourceBundleModel;

public class CustomerInterceptor extends InterceptorAdapter {

	@Override
	public boolean preHandle(WebContext rc, Object handler)
			throws Exception {
		User user = User.getLoginUser(rc);
		
		String url = rc.getURI();
		if (url.startsWith("/admin") && !url.startsWith("/admin/login")) {
			if (user == null || user.getRole() < IUser.ROLE_TOP) {
				rc.error(403);
				return false;
			}
		}
		
		Method methodOfAction = (Method)handler;
		if (methodOfAction.isAnnotationPresent(Annotation.UserRoleRequired.class)) {
			User loginUser = User.getLoginUser(rc); 
			if (loginUser == null) {
				throw new ActionException("user not login");
			}
			if (loginUser.isBlocked()) {
				throw new ActionException("user is blocked");
			}

			Annotation.UserRoleRequired urr = (Annotation.UserRoleRequired) methodOfAction
					.getAnnotation(Annotation.UserRoleRequired.class);
			if (loginUser.getRole() < urr.role()) {// role越大，等级越高。
				throw new ActionException("user deny");
			}
		}
		
		Locale locale = rc.getLocale();
		ResourceBundle resourceBundle = ResourceUtils.getResourceBundle(locale, "messages");
		ResourceBundleModel rsbm = new ResourceBundleModel(resourceBundle, new BeansWrapper());
		rc.setRequestAttr("bundle", rsbm);
		rc.setRequestAttr("rc", rc);
		
		rc.setRequestAttr(Constants.LOGIN_USER, user);
		return true;
	}
}
